using System;
using System.Web;
using System.Web.UI;
using System.IO;
using Microsoft.SharePoint;

namespace Components2.CustomAdmin {

    public class CustomMasterPageModule : IHttpModule {

        public static readonly string CUSTOM_MASTER_PAGE = "c2_custommasterpage";

        public void Init(HttpApplication context) {
            context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
        }

        void context_PreRequestHandlerExecute(object sender, EventArgs e) {
            Page page = HttpContext.Current.CurrentHandler as Page;
            if(page != null) {
                page.PreInit += new EventHandler(page_PreInit);
            }
        }

        void page_PreInit(object sender, EventArgs e) {
            Page page = sender as Page;
            if(page != null) {
                if(page.MasterPageFile != null) {
                    if(page.MasterPageFile.EndsWith("application.master")) {
                        string masterpagefile = null;
                        if (SPContext.Current != null) {
                            SPWeb rootweb = SPContext.Current.Site.RootWeb;
                            if(rootweb.Properties.ContainsKey(CUSTOM_MASTER_PAGE)) {
                                string tmp = rootweb.Properties[CUSTOM_MASTER_PAGE];
                                if (!string.IsNullOrEmpty(tmp)) {
                                    SPFile file = null;
                                    try {
                                        file = rootweb.GetFile(tmp);
                                    } catch {

                                    }
                                    if (file != null && file.Exists) {
                                        masterpagefile = tmp;
                                    }
                                }
                            }
                        } else {
                            //note: for dev website (no sharepoint)
                            masterpagefile = "_catalogs/masterpage/customapplication.master";
                        }
                        if (masterpagefile != null) {
                            page.MasterPageFile = masterpagefile;
                        }
                    }
                }
            }
        }

        public void Dispose() {

        }
    }
}